package com.bootdo.common.sms.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.bootdo.common.sms.model.SmsType;
import com.bootdo.common.sms.service.AliSms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Optional;

@Service
public class AliSmsImpl implements AliSms {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    static final String product = "Dysmsapi";
    static final String domain = "dysmsapi.aliyuncs.com";

    private static String accessKeyId;

    private static String accessSecret;

    private static String smsSignName;

    private static String xdOrderCreate;

    private static String xdOrderWarn;

    private static String xdOrderFinish;

    private static String xdXcxBind;

    private IAcsClient client = null;

    public AliSmsImpl() {

    }

    @PostConstruct                                 //方式1
    public void initClient(){
        DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessSecret);
        this.client = new DefaultAcsClient(profile);
    }

    @Override
    public boolean send(String phoneNumbers, String signName, SmsType smsType,String templateParam) {
        if("易文浩的故障报修".equals(smsSignName)){
            logger.info("测试账户不允许发送短信");
            return true;
        }
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain(domain);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", "".equals(signName)?smsSignName:signName);
        request.putQueryParameter("TemplateCode", getTemplateCodeBySmsType(smsType));
        request.putQueryParameter("TemplateParam", templateParam);
        Optional<CommonResponse> response = null;
        try {
             response = Optional.ofNullable(client.getCommonResponse(request));
             System.out.println(response.map(r-> r.getData()).orElse(""));
            //JSONUtils.jsonToBean(response.getData(), SendSmsResponse.class);
            //{"Message":"OK","RequestId":"4BC5DCF7-EC49-45A0-8D9C-0CC17B10AECB","BizId":"888417057034302278^0","Code":"OK"}
        } catch (ServerException e) {
            e.printStackTrace();
            this.logger.error("@@@ SmsSender phoneNumbers=" + phoneNumbers + ",templateCode"+smsType.toString() + ",templateParam=" + templateParam + " send failed! response data is:" + response.map(r->r.getData()).orElse(""));
            return false;
        } catch (ClientException e) {
            e.printStackTrace();
            this.logger.error("@@@ SmsSender phoneNumbers=" + phoneNumbers + ",templateCode=" +smsType.toString()+ ",templateParam=" + templateParam + " send failed! response data is:" + response.map(r->r.getData()).orElse(""));
            return false;
        }
        this.logger.info("*** ^-^ *** SmsSender send success!  phoneNumbers=" + phoneNumbers + ",templateCode="+smsType.toString() + ",templateParam=" + templateParam);
        return true;
    }

    public static String getTemplateCodeBySmsType(SmsType type) {
        switch(type) {
            case XD_ORDER_CREATE:
                return xdOrderCreate;
            case XD_ORDER_WARN:
                return xdOrderWarn;
            case XD_ORDER_FINISH:
                return xdOrderFinish;
            case XD_XCX_BIND:
                return xdXcxBind;
            default:
                return null;
        }
    }

    @Value("${sms.ali.access.key.id}")
    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    @Value("${sms.ali.access.secret}")
    public void setAccessSecret(String accessSecret) {
        this.accessSecret = accessSecret;
    }

    @Value("${sms.ali.sign.name}")
    public void setSmsSignName(String smsSignName) {
        this.smsSignName = smsSignName;
    }

    @Value("${sms.ali.xd.order.create}")
    public void setXdOrderCreate(String xdOrderCreate) {
        this.xdOrderCreate = xdOrderCreate;
    }

    @Value("${sms.ali.xd.order.warn}")
    public void setXdOrderWarn(String xdOrderWarn) {
        this.xdOrderWarn = xdOrderWarn;
    }

    @Value("${sms.ali.xd.order.finish}")
    public void setXdOrderFinish(String xdOrderFinish) {
        this.xdOrderFinish = xdOrderFinish;
    }

    @Value("${sms.ali.xd.xcx.bind}")
    public void setXdXcxBind(String xdXcxBind) {
        this.xdXcxBind = xdXcxBind;
    }
}
